<template>
  <div class="app-container">
    <div class="fly-card-head">
      <div class="fly-card-head-wrapper">
        <div class="fly-card-head-title"><div class="head-title">行政区域列表</div></div>
      </div>
    </div>
    <div class="fly-card-body">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="行政区域名称" prop="regionName">
          <el-input v-model="queryParams.regionName" placeholder="请输入行政区域名称" clearable size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:region:add']">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="regionList" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="区域名称" align="left" prop="regionName" />
        <el-table-column label="区域父ID" align="center" prop="parentId" />
        <el-table-column label="区域类型" align="center" prop="regionType" />
        <el-table-column label="区域编码" align="center" prop="regionCode" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:region:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:region:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改行政区域对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="父ID" prop="parentId">
            <treeselect
              v-model="form.parentId"
              :options="regionOptions"
              :normalizer="normalizer"
              placeholder="请选择行政区域父ID，例如区县的pid指向市，市的pid指向省，省的pid则是0"
            />
          </el-form-item>
          <el-form-item label="区域名称" prop="regionName"><el-input v-model="form.regionName" placeholder="请输入行政区域名称" /></el-form-item>
          <el-form-item label="区域类型">
            <el-select v-model="form.regionType" placeholder="请选择行政区域类型，如如1则是省， 如果是2则是市，如果是3则是区县">
              <el-option label="请选择字典生成" value="" />
            </el-select>
          </el-form-item>
          <el-form-item label="行政区域编码" prop="regionCode"><el-input v-model="form.regionCode" placeholder="请输入行政区域编码" /></el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listRegion, getRegion, delRegion, addRegion, updateRegion, exportRegion } from '@/api/system/region';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: 'Region',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 行政区域表格数据
      regionList: [],
      // 行政区域树选项
      regionOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        regionName: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [{ required: true, message: '行政区域父ID，例如区县的pid指向市，市的pid指向省，省的pid则是0不能为空', trigger: 'blur' }],
        regionName: [{ required: true, message: '行政区域名称不能为空', trigger: 'blur' }],
        regionType: [{ required: true, message: '行政区域类型，如如1则是省， 如果是2则是市，如果是3则是区县不能为空', trigger: 'blur' }],
        regionCode: [{ required: true, message: '行政区域编码不能为空', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询行政区域列表 */
    getList() {
      this.loading = true;
      listRegion(this.queryParams).then(response => {
        this.regionList = this.handleTree(response.data, 'id', 'parentId');
        this.loading = false;
      });
    },
    /** 转换行政区域数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.regionName,
        children: node.children
      };
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listRegion().then(response => {
        this.regionOptions = [];
        const data = { id: 0, regionName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, 'id', 'parentId');
        this.regionOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        regionName: undefined,
        regionType: undefined,
        regionCode: undefined
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.open = true;
      this.title = '添加行政区域';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      getRegion(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改行政区域';
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateRegion(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功');
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addRegion(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功');
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除行政区域编号为"' + row.id + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delRegion(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess('删除成功');
        })
        .catch(function() {});
    }
  }
};
</script>
